package com.warmlight.voicepacket.ui.communitylm.widget;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.OSSRequest;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.bean.cdetails.CDetailsListBean;
import com.warmlight.voicepacket.bean.comm.RecommPictureBean;
import com.warmlight.voicepacket.bean.comm.UserBean;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.HttpUtils;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.ui.communitylm.adapter.ReplyImgAdapter;
import com.warmlight.voicepacket.ui.user.LoginRegistActivity;
import com.warmlight.voicepacket.utils.KeyboardUtils;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 回复框 真正的回复框，用于回复文字图片等
 */
public class ReplyBar extends RelativeLayout implements View.OnClickListener, ReplyImgAdapter.PhotoCallBack {

    private RecyclerView rc_imgs;
    private EditText et_reply;
    private TextView tv_reply;
    private ArrayList<LocalMedia> imgs;
    private ArrayList<String> success;
    private ArrayList<String> failed;
    private ReplyImgAdapter adapter;
    private ImageView iv_add_img;
    private int type;
    private String post_id;
    private String reply_id;
    private String to_uid;

    /**
     * 设置回复消息类型
     * type 0 回复帖子 1 回复评论  2回复某个人
     * treeMap.put("post_id","");//帖子id
     treeMap.put("reply_id","");//评论ID 0:表示评论帖子 不为0标识回复评论
     treeMap.put("to_uid","");//用户ID 不为0：表示回复某个人
     */
    public void setReplyBar(int type ,String post_id,String reply_id,String to_uid){
        this.type = type;
        this.post_id = post_id;
        this.reply_id = reply_id;
        this.to_uid = to_uid;
    }

    public void setReplyBarHint(String hint){
        et_reply.setHint(hint);
    }

    /**
     * 设置回复框显示与隐藏
     * @param isShow
     */
    public void showReplyBar(boolean isShow,boolean isShowKeyboard){
        if (isShow){
            this.setVisibility(VISIBLE);
            if (isShowKeyboard){
                et_reply.requestFocus();
                KeyboardUtils.openKeybord(et_reply,getContext());
            }
        }else{
            this.setVisibility(GONE);
        }
    }

    /**
     * 外部点击
     */
    public void setOnTouch(){
//        if (KeyboardUtils.isSHowKeyboard( getContext(),et_reply)){
            KeyboardUtils.HideKeyboard(et_reply);
//        }else{
//                    ToastUtil.showShort(getContext(),"隐藏回复框");
            showReplyBar(false,false);
//        }
    }

    @Override
    public void addPhoto() {
        int itemCount = adapter.getItemCount();
        if (itemCount == 0){
            itemCount = 9;
        }else {
            if (TextUtils.equals("addImg",imgs.get(itemCount-1).getPath())){
                itemCount = 9-itemCount+1;
            }else{
                ToastUtil.showShort(getContext(),"已选择9张图片");
                return;
            }
        }
        pickPhoto(itemCount);
    }

    @Override
    public void deletePhoto(int position) {

    }

    @Override
    public void showImg(boolean show) {
        if (show){
            iv_add_img.setVisibility(VISIBLE);
        }else{
            iv_add_img.setVisibility(GONE);
        }
    }

    private ReplyBarReplySuccessLisener replyBarLisener;

    public interface ReplyBarReplySuccessLisener{
        void success(CDetailsListBean data);
    }

    public void setOnReplyBarLisener(ReplyBarReplySuccessLisener replyBarLisener){
        this.replyBarLisener = replyBarLisener;
    }

    public ReplyBar(Context context) {
        super(context);
        init(context);
    }

    public ReplyBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ReplyBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        LayoutInflater.from(context).inflate(R.layout.replay_bar,this,true);
        initView();
        initlisener();
        initData();
    }

    private void initData() {
        LinearLayoutManager manager = new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false);
        rc_imgs.setLayoutManager(manager);
        imgs = new ArrayList<>();
        adapter = new ReplyImgAdapter(getContext(),this, imgs);
        rc_imgs.setAdapter(adapter);

        success = new ArrayList<>();
        failed = new ArrayList<>();
    }

    private void initlisener() {
        tv_reply.setOnClickListener(this);
        iv_add_img.setOnClickListener(this);
//        et_reply.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                sendMsg();
//                return false;
//            }
//        });
    }

    private void initView() {
        iv_add_img = findViewById(R.id.iv_add_img);
        rc_imgs = findViewById(R.id.rc_imgs);
        et_reply = findViewById(R.id.et_reply);
        tv_reply = findViewById(R.id.tv_reply);

        LinearLayout ll_click = findViewById(R.id.ll_click);
        ll_click.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        rc_imgs.setVisibility(GONE);
        iv_add_img.setVisibility(VISIBLE);
        showReplyBar(false,false);
    }

    /**
     * 点击发送后进行发送前准备
     */
    private void sendMsg(){
        String replyText = et_reply.getText().toString().trim();
        if (TextUtils.isEmpty(replyText) && imgs.size() == 0){
            ToastUtil.showShort(getContext(),"请输入回复信息");
            return;
        }

        if (!SPUtils.isLogined()){
            KeyboardUtils.HideKeyboard(et_reply);
//            ToastUtil.showShort(getContext(),"请先登录");
            getContext().startActivity(new Intent(getContext(), LoginRegistActivity.class));
            return;
        }

        KeyboardUtils.HideKeyboard(et_reply);

        LoadingView loadingView = new LoadingView(getContext());
        loadingView.show();
        ArrayList<LocalMedia> selectImg = new ArrayList<>();
        for (int i=0;i<imgs.size();i++){
            LocalMedia localMedia = imgs.get(i);
            String path = localMedia.getPath();
            if (!TextUtils.equals("addImg",path)){
                selectImg.add(localMedia);
            }
        }
        if (selectImg.size()>0){
            success.clear();
            failed.clear();
            sendImgToAli(selectImg,replyText,loadingView);
        }else{
            reply(selectImg,replyText,loadingView);
        }

    }


    /**
     * 上传图片到阿里云
     * @param imgs
     * @param replyText
     * @param loadingView
     */
    private void sendImgToAli(final ArrayList<LocalMedia> imgs, final String replyText, final LoadingView loadingView){
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(final ObservableEmitter<String> emitter) throws Exception {
                for (LocalMedia localMedia :imgs){
                    String s = localMedia.getPath();
                    final File file = new File(s);
                    if (!file.exists()) {

                        continue;
                    }
                    final String object = HttpConfig.replyImg()+file.getName();
                    if (object.equals("")) {
                        Log.w("AsyncPutImage", "ObjectNull");
                        continue;
                    }

                    localMedia.setCutPath(object);


                    // 构造上传请求
                    PutObjectRequest put = new PutObjectRequest(HttpConfig.bucket, object, s);
                    put.setCRC64(OSSRequest.CRC64Config.YES);
//        if (mCallbackAddress != null) {
//            // 传入对应的上传回调参数，这里默认使用OSS提供的公共测试回调服务器地址
//            put.setCallbackParam(new HashMap<String, String>() {
//                {
//                    put("callbackUrl", mCallbackAddress);
//                    //callbackBody可以自定义传入的信息
//                    put("callbackBody", "filename=${object}");
//                }
//            });
//        }

                    // 异步上传时可以设置进度回调
                    put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                        @Override
                        public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
//                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
//                int progress = (int) (100 * currentSize / totalSize);
//                mDisplayer.updateProgress(progress);
//                mDisplayer.displayInfo("上传进度: " + String.valueOf(progress) + "%");

                        }
                    });

                    OSSAsyncTask task = getOSS().asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                        @Override
                        public void onSuccess(PutObjectRequest request, PutObjectResult result) {
//                            OSSLog.logDebug("upload cost: " + (upload_end - upload_start) / 1000f);
//                mDisplayer.uploadComplete();
//                mDisplayer.displayInfo("Bucket: " + mBucket
//                        + "\nObject: " + request.getObjectKey()
//                        + "\nETag: " + result.getETag()
//                        + "\nRequestId: " + result.getRequestId()
//                        + "\nCallback: " + result.getServerCallbackReturnBody());
                            String objectKey = request.getObjectKey();
                            success.add(HttpConfig.ali + object);

                            if ((success.size() + failed.size())==imgs.size()){
                                emitter.onNext("1");
                                emitter.onComplete();
                            }
                        }

                        @Override
                        public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                            String info = "";
                            // 请求异常
                            if (clientExcepion != null) {
                                // 本地异常如网络异常等
                                clientExcepion.printStackTrace();
                                info = clientExcepion.toString();
                            }
                            if (serviceException != null) {
                                // 服务异常
//                                Log.e("ErrorCode", serviceException.getErrorCode());
//                                Log.e("RequestId", serviceException.getRequestId());
//                                Log.e("HostId", serviceException.getHostId());
//                                Log.e("RawMessage", serviceException.getRawMessage());
//                                info = serviceException.toString();
                            }

                            failed.add(request.getUploadFilePath());
                            if ((success.size() + failed.size())==imgs.size()){
                                emitter.onNext("1");
                                emitter.onComplete();
                            }
                        }
                    });
                }

            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String o) {
                        if (success.size() == imgs.size()){
                            //todo
                            reply(imgs,replyText,loadingView);
                        }else{
                            //todo
                            ToastUtil.showShort(getContext(),"图片上传失败，请重试");
                            loadingView.dismiss();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
//                        if (loadingView != null){
//                            loadingView.dismiss();
//                        }
                    }
                });


    }

    /**
     * 获取图片上传后的json 数据
     * [{"w":0,"h":0,"u":"","is_gif":false}]
     * @param imgs
     */
    private String getJson(ArrayList<LocalMedia> imgs){
        if (imgs.size() == 0){
            return "";
        }
        JSONArray jsonArray = new JSONArray();
        for (int i=0;i<imgs.size();i++){
            LocalMedia localMedia = imgs.get(i);
            int width = localMedia.getWidth();
            int height = localMedia.getHeight();
//            String path = localMedia.getPath();
            String pictureType = localMedia.getPictureType();
//            File file = new File(path);
//            String object = HttpConfig.replyImg()+file.getName();
            String object = localMedia.getCutPath();
            String url = HttpConfig.ali + object;
            JSONObject jsonObject = new JSONObject();
            boolean gif = PictureMimeType.isGif(pictureType);
            try {
                jsonObject.put("w",width);
                jsonObject.put("h",height);
                jsonObject.put("u",url);
                jsonObject.put("is_gif",gif);
                jsonArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        String s = jsonArray.toString();
        return s;
    }

    /**
     * 发布评论成功后，清除输入框和图片列表，恢复初始状态
     */
    private void replySuccess(){
        et_reply.setText("");
        if (adapter != null){
            adapter.clearAll();
        }
    }

    /**
     * 上传数据到我们的后台
     * @param imgs
     * @param msg
     * @param loadingView
     */
    private void reply(ArrayList<LocalMedia> imgs,String msg,final LoadingView loadingView){
        String json = getJson(imgs);
        String url = HttpConfig.ADD_REPLY;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("post_id",post_id);//帖子id
        treeMap.put("reply_id",reply_id);//评论ID 0:表示评论帖子 不为0标识回复评论
        treeMap.put("to_uid",to_uid);//用户ID 不为0：表示回复某个人
        treeMap.put("content",msg);//评论内容
        treeMap.put("pics",json);//图片 json [{"w":0,"h":0,"u":"","is_gif":false}]
        HttpClient.getInstance().postRxAndroidAES(url,treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {
                        if (HttpUtils.isCodeSuccess(responseData.getCode())){
                            ToastUtil.showShort(getContext(),"评论成功");
                            replySuccess();

                            success(responseData.getData());


                        }else{
                            ToastUtil.showShort(getContext(),responseData.getMsg());
                        }
                        loadingView.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.showShort(getContext(),"发送失败，请稍后重试");
                        loadingView.dismiss();
                    }

                    @Override
                    public void onComplete() {
//                        loadingView.dismiss();
                    }
                });
    }

    /**
     * {"uid":"162830","content":"你好","pics":[],"post_id":342,"reply_id":0,"to_uid":0,"status":2,"add_time":1536757336,"id":0}
     *
     * /**
     * id : 75437
     * post_id : 342
     * content : 不扎的慌么
     * like_num : 0
     * is_like : false
     * is_god : 0
     * reply_num : 0
     * date : 27天前
     * pics : []
     * user : {"uid":"124332","nickname":"爱吾不死","avator":"https://nuanguang-img.oss-cn-shanghai.aliyuncs.com/post/avator/a8877460bb8cad0f717f19771bcde6b8_1535810314.jpg","sex":"0"}
     *private String id;
     private String post_id;
     private String content;
     private int like_num;
     private int is_like;
     private String is_god;
     private String reply_num;
     private String date;
     private UserBeanX user;
     private List<PicsBean> pics;
     */
    private void success(String data) {
        try {
            CDetailsListBean replyListBean = new CDetailsListBean();
//                    PostDetalData.ReplyListBean replyListBean = new PostDetalData.ReplyListBean();

            JSONObject jsonObject = new JSONObject(data);

            String id = jsonObject.optString("id");
            String post_id = jsonObject.optString("post_id");
            String content = jsonObject.optString("content");
            String like_num = jsonObject.optString("like_num");
            int is_like = jsonObject.optInt("is_like");
            String is_god = jsonObject.optString("is_god");
            String reply_num = jsonObject.optString("reply_num");
            String date = jsonObject.optString("date");

            JSONObject user = jsonObject.optJSONObject("user");
            String uid = user.optString("uid");
            String nickname = user.optString("nickname");
            String avator = user.optString("avator");
            String sex = user.optString("sex");

            UserBean userBeanX = new UserBean();
            userBeanX.setUid(uid);
            userBeanX.setNickname(nickname);
            userBeanX.setAvator(avator);
            userBeanX.setSex(sex);

            JSONArray jsonArray = jsonObject.optJSONArray("pics");
            List<RecommPictureBean> pics = new ArrayList<>();
            for (int i=0;i<jsonArray.length();i++){
                JSONObject o = (JSONObject) jsonArray.get(i);
                String w = o.optString("w");
                String h = o.optString("h");
                String u = o.optString("u");
                String is_gif = o.optString("is_gif");

                RecommPictureBean picsBean = new RecommPictureBean();
                picsBean.setW(w);
                picsBean.setH(h);
                picsBean.setU(u);
                if (is_gif.equals("0")){
                    picsBean.setIs_gif(true);

                }else{
                    picsBean.setIs_gif(false);
                }
                pics.add(picsBean);
            }

            replyListBean.setId(id);
            replyListBean.setPost_id(post_id);
            replyListBean.setContent(content);
            replyListBean.setLike_num(like_num);
            replyListBean.setIs_like(is_like);
            replyListBean.setIs_god(is_god);
            replyListBean.setReply_num(reply_num);
            replyListBean.setDate(date);
            replyListBean.setUser(userBeanX);
            replyListBean.setPics(pics);

            if (replyBarLisener != null){
                replyBarLisener.success(replyListBean);
            }
//                    list.add(1,replyListBean);
//                    if (adapter != null){
//                        adapter.notifyDataSetChanged();
//                    }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取阿里OSS
     */
    private OSS mOss;
    private OSS getOSS(){
        if (mOss == null) {
            String endpoint = HttpConfig.endpoint;
            String stsServer = "STS应用服务器地址，例如http://abc.com";
//推荐使用OSSAuthCredentialsProvider。token过期可以及时更新
            OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(HttpConfig.accessKeyId, HttpConfig.accessKeySecret);
//该配置类如果不设置，会有默认配置，具体可看该类
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
            conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
            conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
            mOss = new OSSClient(getContext().getApplicationContext(), endpoint, credentialProvider);
        }
        return mOss;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_reply:
//                if (replyBarLisener != null){
//                    replyBarLisener.photoPick();
//                }
//                photoPick();
//                addPhoto();
                sendMsg();
                break;
            case R.id.iv_add_img:
                addPhoto();
                break;
        }
    }

    /**
     *在用到的activity 或者 fragment中重写onActivityResult调用次方法
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ((Activity)getContext()).RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    if (selectList.size()>0) {
//                        ArrayList<String> a = new ArrayList<>();
//                        for (LocalMedia localMedia : selectList) {
//                            a.add(localMedia.getPath());
//                        }
                        adapter.addImgs(selectList);
                    }
//                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }
    /**
     * 重写view所在activity的onActivityResult 调用 replybar的onActivityResult
//     * @param requestCode
//     * @param resultCode
//     * @param data
     */
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
//            if (data != null && requestCode == 10) {
//                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
//                if (images != null && images.size()>0){
//
//                }
//            } else {
//                ToastUtil.showShort(getContext(), "没有数据");
//            }
//        }
//    }

//    private void photoPick() {
//        int size = imgs.size();
//        if (size == 0){
//            size = 9;
//        }else if (size < 9){
//            size = 9-size;
//        }else{
//            ToastUtil.showShort(getContext(),"已选择9张图片");
//            return;
//        }
//
//        ImagePicker imagePicker = ImagePicker.getInstance();
//        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
//        imagePicker.setShowCamera(true);  //显示拍照按钮
//        imagePicker.setMultiMode(true);  //多选
////        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
//        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
//        imagePicker.setSelectLimit(size);    //选中数量限制(最多9张)
////        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
////        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
////        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
////        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
////        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
//
//        Intent intent = new Intent(getContext(), ImageGridActivity.class);
//        ((Activity)getContext()).startActivityForResult(intent, 10);
//    }

    /**
     * 吊起图片选择框
     * @param max 可选图片数量，随着已选图片的变化而变化，最多九张
     */
    private void pickPhoto(int max){
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create((Activity) getContext())
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_QQ_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(max)// 最大图片选择数量 int
                .minSelectNum(0)// 最小选择数量 int
                .imageSpanCount(3)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .previewVideo(false)// 是否可预览视频 true or false
                .enablePreviewAudio(false) // 是否可播放音频 true or false
                .isCamera(false)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                .enableCrop(false)// 是否裁剪 true or false
                .compress(false)// 是否压缩 true or false
                .glideOverride(160,160)// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                .hideBottomControls()// 是否显示uCrop工具栏，默认不显示 true or false
                .isGif(true)// 是否显示gif图片 true or false
//                .compressSavePath(getPath())//压缩图片保存地址
//                .freeStyleCropEnabled()// 裁剪框是否可拖拽 true or false
//                .circleDimmedLayer()// 是否圆形裁剪 true or false
//                .showCropFrame()// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
//                .showCropGrid()// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
//                .openClickSound()// 是否开启点击声音 true or false
//                .selectionMedia()// 是否传入已选图片 List<LocalMedia> list
//                .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
//                .cropCompressQuality()// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
//                .synOrAsy(true)//同步true或异步false 压缩 默认同步
//                .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
//                .rotateEnabled() // 裁剪是否可旋转图片 true or false
//                .scaleEnabled()// 裁剪是否可放大缩小图片 true or false
//                .videoQuality()// 视频录制质量 0 or 1 int
//                .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
//                .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
//                .recordVideoSecond()//视频秒数录制 默认60s int
//                .isDragFrame(false)// 是否可拖动裁剪框(固定)
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        ((Activity)getContext()).overridePendingTransition(R.anim.dialog_in_from_right, R.anim.no_anim);
    }
}
